// electron/preload.js
const { contextBridge, ipcRenderer } = require('electron');

console.log('Preload script is starting...');

// 定义要暴露给渲染进程的 API
const electronAPI = {
  ipcRenderer: {
    invoke: (...args) => {
      console.log('Invoking with args:', args);
      return ipcRenderer.invoke(...args);
    },
    on: (channel, func) => {
      const subscription = (event, ...args) => func(...args);
      ipcRenderer.on(channel, subscription);
      return () => {
        ipcRenderer.removeListener(channel, subscription);
      };
    },
    once: (channel, func) => {
      ipcRenderer.once(channel, (event, ...args) => func(...args));
    },
    removeListener: (channel, func) => {
      ipcRenderer.removeListener(channel, func);
    },
    removeAllListeners: (channel) => {
      ipcRenderer.removeAllListeners(channel);
    }
  }
};

// 添加版本信息和调试信息
const debugInfo = {
  versions: process.versions,
  preloadPath: __filename,
  timestamp: Date.now()
};

// 暴露 API 到渲染进程
try {
  console.log('Debug info:', debugInfo);
  console.log('Exposing electron API to window...');
  contextBridge.exposeInMainWorld('electron', electronAPI);
  contextBridge.exposeInMainWorld('debugInfo', debugInfo);
  console.log('Successfully exposed electron API');
} catch (error) {
  console.error('Failed to expose electron API:', error);
}

// 添加一个测试 API 调用
contextBridge.exposeInMainWorld('electronAPI', {
  test: () => console.log('Electron API is working!')
});
